//
//  EHTableViewDataSource.swift
//  ExtremeHealth
//
//  Created by Zhongkai Li 李忠凯 on 2018/9/19.
//  Copyright © 2018 GanDongKeJi. All rights reserved.
//

import UIKit

class TableViewDataSource<Model>: NSObject, UITableViewDataSource {
    typealias CellConfigurator = (Model, UITableViewCell) -> Void

    var models: [Model]

    private let reuseIdentifier: String
    private let cellConfigurator: CellConfigurator

    init(models: [Model],
         reuseIdentifier: String,
         cellConfigurator: @escaping CellConfigurator) {
        self.models = models
        self.reuseIdentifier = reuseIdentifier
        self.cellConfigurator = cellConfigurator
    }

    func tableView(_ tableView: UITableView,
                   numberOfRowsInSection section: Int) -> Int {
        return models.count
    }

    func tableView(_ tableView: UITableView,
                   cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = models[indexPath.row]
        let cell = tableView.dequeueReusableCell(
            withIdentifier: reuseIdentifier,
            for: indexPath
        )

        cellConfigurator(model, cell)

        return cell
    }
}

//extension TableViewDataSource where Model == Message {
//    static func make(for messages: [Message],
//                     reuseIdentifier: String = "message") -> TableViewDataSource {
//        return TableViewDataSource(
//            models: messages,
//            reuseIdentifier: reuseIdentifier
//        ) { (message, cell) in
//            cell.textLabel?.text = message.title
//            cell.detailTextLabel?.text = message.preview
//        }
//    }
//}
